package com.mediocre.util;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.mediocre.constant.Constant;
import com.mediocre.entity.Post;
import com.mediocre.entity.PostHalo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Map;

/**
 * 业务相关的工具类
 */
@Slf4j
public class BizUtils {


    public static void configRequest(HttpRequestBase httpRequest) {
        RequestConfig requestConfig = RequestConfig.custom()
                // 设置连接超时时间(单位毫秒)
                .setConnectTimeout(Constant.CONNECT_TIMEOUT)
                // 设置请求超时时间(单位毫秒)
                .setConnectionRequestTimeout(Constant.CONNECTION_REQUEST_TIMEOUT)
                // socket读写超时时间(单位毫秒)
                .setSocketTimeout(Constant.SOCKET_TIMEOUT)
                // 设置是否允许重定向(默认为true)
                .setRedirectsEnabled(Constant.REDIRECTS_ENABLED).build();

        // 设置请求配置信息
        httpRequest.setConfig(requestConfig);
        // 设置请求头信息
        httpRequest.setHeader("User-Agent", Constant.USER_AGENT);
        httpRequest.setHeader("Accept-Encoding", Constant.ACCEPT_ENCODING);
        httpRequest.setHeader("Connection", Constant.CONNECTION);
        httpRequest.setHeader("accept", Constant.ACCEPT);
        httpRequest.setHeader("accept-language", Constant.ACCEPT_LANGUAGE);
        httpRequest.setHeader("content-type", Constant.CONTENT_TYPE);
        httpRequest.setHeader("cookie", Constant.COOKIE);
        httpRequest.setHeader("referer", Constant.REFERER);
        httpRequest.setHeader("sec-fetch-dest", Constant.SEC_FETCH_DEST);
        httpRequest.setHeader("sec-fetch-mode", Constant.SEC_FETCH_MODE);
        httpRequest.setHeader("sec-fetch-site", Constant.SEC_FETCH_SITE);
        if (httpRequest instanceof HttpDelete)
            httpRequest.setHeader("x-xsrf-token", Constant.X_XSRF_TOKEN_DELETE);
        else if (httpRequest instanceof HttpPost)
            httpRequest.setHeader("x-xsrf-token", Constant.X_XSRF_TOKEN_POST);
    }

    public static void closeResources(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) {
        if (httpResponse != null) {
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getResponseStr(HttpResponse httpResponse) throws IOException {
        log.info("response status -> {}", httpResponse.getStatusLine());
        // 从响应模型中获取响应实体
        HttpEntity responseEntity = httpResponse.getEntity();
        if (responseEntity == null) return null;
        String responseStr = EntityUtils.toString(responseEntity);
        log.info("response content -> {}", responseStr);
        // 该响应内容长度总是为 -1，查询原因并解决（已解决）
        // log.info("response content's length -> {}", responseEntity.getContentLength());  // 可能是因为服务器对响应内容压缩了，所以该值永远是 -1，使用下面的方法来获取响应内容长度
        log.info("response content's length -> {} character(s)", responseStr.length());
        return responseStr;
    }

    /**
     * 获取泛型的Collection Type
     * @param collectionClass 泛型的Collection
     * @param elementClasses 元素类
     * @return JavaType Java类型
     * @since 1.0
     */
    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        CollectionType listType = Constant.OBJECTMAPPER.getTypeFactory().constructCollectionType(ArrayList.class, Map.class);
        return Constant.OBJECTMAPPER.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

    public static Post buildPost(PostHalo postHalo) {
        String postHaloTitle = postHalo.getTitle();
        int accessPermission = 0;
        if (("#J#K#各个框架的启动与停止命令#J#K#大数据集群环境准备#J#K#大数据80道面试题#J#K#jobhunt#J#K#bdreview1#J#K#bdreview2#J#K#bdreview3#J#K#bdreview4" +
                "#J#K#linux系统for大数据#J#K#五险一金个税抵扣等#J#K#todo#J#K#thinking#J#K#").contains(postHaloTitle))
            accessPermission = 268435456;
        Post p = new Post();
        p.setId(null);
        p.setPostType((byte) 1);
        p.setAccessPermission(accessPermission);
        p.setTitle(postHaloTitle);
        p.setUrl(null);
        p.setPostBody(postHalo.getOriginalContent());
        p.setCategoryIds(new Integer[]{1356051});
        p.setInSiteCandidate(false);
        p.setInSiteHome(false);
        p.setSiteCategoryId(null);
        p.setBlogTeamIds(null);
        p.setIsPublished(true);
        p.setDisplayOnHomePage(true);
        p.setIsAllowComments(true);
        p.setIncludeInMainSyndication(true);
        p.setIsPinned(false);
        p.setIsOnlyForRegisterUser(false);
        p.setIsUpdateDateAdded(false);
        p.setEntryName(null);
        p.setDescription(null);
        p.setFeaturedImage(null);

        String[] split = postHaloTitle.split("_");
        if (split.length > 1)
            p.setTags(new String[]{split[1]});
        else
            p.setTags(null);
        p.setPassword(null);
        p.setDatePublished(LocalDateTime.now().toString());
        p.setIsMarkdown(true);
        p.setIsDraft(true);
        p.setAutoDesc(null);
        p.setChangePostType(false);
        p.setBlogId(0);
        p.setAuthor(null);
        p.setRemoveScript(false);
        p.setClientInfo(null);
        p.setChangeCreatedTime(false);
        p.setCanChangeCreatedTime(false);
        // post.setFeedBackCount();
        // post.setWebCount();
        // post.setAggCount();
        // post.setViewCount();
        // post.setPostConfig();
        return p;
    }
}
